(function() {
	var mapInit = function() {
		var lon = $J('#lon').val();
		var lat = $J('#lat').val();
		var map = new BMap.Map("l-map");
		map.enableScrollWheelZoom();//启用地图滚轮放大缩小
		var point;
		var mk;
		if (lon) {
			point = new BMap.Point(lon, lat);
			map.centerAndZoom(point,13);
			mk = new BMap.Marker(point);
			map.addOverlay(mk);
	        mk.enableDragging();
			map.panTo(point);
			showLocationInfo(lon, lat);
			mk.addEventListener("dragend", function(e){
				showLocationInfo(e.point.lng, e.point.lat);
			});
		} else {
			point = new BMap.Point(116.331398, 39.897445);
			map.centerAndZoom(point,12);
			var geolocation = new BMap.Geolocation();
			geolocation.getCurrentPosition(function(r){
				if(this.getStatus() == BMAP_STATUS_SUCCESS){
					mk = new BMap.Marker(r.point);
					map.addOverlay(mk);
		            mk.enableDragging();
					map.panTo(r.point);
					showLocationInfo(r.point.lng, r.point.lat);
					// 拖拽监听
					mk.addEventListener("dragend", function(e){
						showLocationInfo(e.point.lng, e.point.lat);
					});
				}      
			},{enableHighAccuracy: true})
		}
	}
	
	var showLocationInfo = function(lon, lat) {
		$J('#posresult').val('');
		$J('#lon').val(lon);
		$J('#lat').val(lat);
	}

	
    $J('body').on('click', '.cfmBtn', function() {
		var p = $J(this).parent();
		var selName = p.find('.selName').val();
		var inputName = p.find('.oninputsearch').val();
		if (selName == inputName) {
			p.find('.cfmValue').val(selName);
			p.find('.cfmId').val(p.find('.selId').val());
		} else {
			p.find('.cfmValue').val('');
			p.find('.cfmId').val('');
		}
	}).on('click', '.addPeriod', function() {
		$J('#periods').clone().insertBefore($J('#last'));
		$J('.timepicker-24').timepicker({
		    autoclose: true,
		    minuteStep: 1,
		    showMeridian: false
		});
	}).on('click', '#savePriceBtn', function() {
		$J('div[name="periodDiv"]').each(function () {
			var startTime = $J(this).find('input[name="startTime"]').val();
			var endTime = $J(this).find('input[name="endTime"]').val();
			var price = $J(this).find('input[name="price"]').val();
			$J(this).find('input[name="period"]').val(startTime + "--" + endTime + "--" + price);
		});
		
		document.ruleForm.submit();
	}).on('click', '#mpbtn', function() {
		var params = {
			'lon' : $J("#lon").val(),
			'lat' : $J("#lat").val()
		};
		ajaxPut(window.baseUrl + '/pd/lot/'+ $J('#id').val() + '/map', JSON.stringify(params), function() {
			$J('#posresult').html('设置成功');
		});
	});
    
	$J('.oninputsearch').attr("autocomplete", "off");
	$J('#selMerchant').autocomplete({
		serviceUrl : window.baseUrl + '/user/merchant/query',
		onSelect : function(suggestion) {
			if ($J('#selMerchantId').length > 0) {
				$J('#selMerchantId').val(suggestion.id);
				$J('#selMerchantName').val(suggestion.name);
			}
		}
	});
	
    $J('.timepicker-24').timepicker({
	    autoclose: true,
	    minuteStep: 1,
	    showMeridian: false
	});
    
    mapInit();
})();
